package concurrent;

import java.util.concurrent.*;

public class FutureTest1 {

    public static void main(String[] args) {

        Callable<Boolean> c = () -> { // about 8s to run
            System.out.println("计算开始");
            long s = System.currentTimeMillis();
            long num = 1000000033L;
            for (long i = 2; i < num; i++) {
                if (num % i == 0) {
                    return false;
                }
            }
            long end = System.currentTimeMillis();
            System.out.println("计算结束 耗时" + (end - s) / 1000 + "秒");
            return true;
        };

        ExecutorService threadPool = Executors.newSingleThreadExecutor();
        Future<Boolean> f = threadPool.submit(c);
        cancelTask(f, 2000);
        long s = System.currentTimeMillis();
        try {
            Boolean b = f.get();
        } catch (InterruptedException e) {
            System.out.println("InterruptedException");
            long end = System.currentTimeMillis();
            System.out.println((end - s) / 1000);
        } catch (ExecutionException e) {
            System.out.println("ExecutionException");
            long end = System.currentTimeMillis();
            System.out.println((end - s) / 1000);
        } catch (CancellationException ex) {
            System.out.println("CancellationException");
            long end = System.currentTimeMillis();
            System.out.println((end - s) / 1000);
        }
    }

    private static void cancelTask(final Future<?> future, final int delay) {

        Runnable cancellation = () -> {
            try {
                Thread.sleep(delay);
                future.cancel(true); // 取消与 future 关联的正在运行的任务
            } catch (InterruptedException ex) {
                ex.printStackTrace(System.err);
            }
        };

        new Thread(cancellation).start();
    }
}

